package com.kaifamiao.wendao.dao;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Explain;
import org.apache.commons.dbutils.ResultSetHandler;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class ExplainDao extends BaseDao<Explain,Long> {

    private static final String FETCH_BY_TOPIC_ID = "SELECT id, content, publish_time, praise, despise, customer_id FROM t_explains WHERE topic_id = ?";
    private static final String INSERT = "INSERT INTO t_explains (id, content, publish_time, publish_address, topic_id, customer_id) VALUES (?,?,?,?,?,?)";
    private ResultSetHandler<List<Explain>> listHandler = rs -> {
        List<Explain> explains = new ArrayList<>();
        while(rs.next()){
            Explain e = new Explain();
            e.setId(rs.getLong("id"));
            e.setContent(rs.getString("content"));
            java.sql.Timestamp time = rs.getTimestamp("publish_time");
            LocalDateTime publishTime = time != null ? time.toLocalDateTime() : null ;
            e.setPublishTime(publishTime);
            e.setPraise(rs.getInt("praise"));
            e.setDespise(rs.getInt("despise"));
            long cid = rs.getLong("customer_id");
            Customer author = new Customer();
            author.setId(cid);
            e.setAuthor(author);
            explains.add(e);
        }
        return explains;
    };

    @Override
    public boolean save(Explain e) {
        try {
            LocalDateTime datetime = e.getPublishTime();
            java.sql.Timestamp time = datetime != null ? java.sql.Timestamp.valueOf(datetime) : null ;
            // 获取被解答话题的标识符
            Long topicId = e.getTopic().getId();
            // 获取发布者的标识符
            Long customerId = e.getAuthor().getId();
            Object[] params = {e.getId(), e.getContent(), time, e.getPublishAddress(), topicId, customerId};
            int count = runner.update(INSERT, params);
            return count == 1;
        } catch (SQLException cause) {
            throw new RuntimeException("保存失败",cause);
        }

    }

    @Override
    public boolean update(Explain explain) {
        return false;
    }

    @Override
    public boolean remove(Long id) {
        return false;
    }

    @Override
    public List<Explain> findAll() {
        return null;
    }

    @Override
    public Explain find(Long id) {
        return null;
    }

    /**
     * 根据话题编号查询与之相关的所有解答
     * @param topicId 作为查询条件使用的话题编号
     * @return 返回与指定话题相关的所有解答
     */
    public List<Explain> findByTopicId(Long topicId) {
        try {
            return runner.query(FETCH_BY_TOPIC_ID, listHandler, topicId);
        }catch (SQLException cause){
            throw new RuntimeException("查询失败",cause);
        }
    }

}
